package com.mosaic.girih;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.mosaic.girih.R;
import com.mosaic.girih.MosaicFilter;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {
	protected MosaicFilter[] mFilters;

	protected static final String settingsFile = "com.mosaic.girih.xml.config.xml";

	protected static final String outFolderKey = "OutputFolder";
	protected static final String outNameKey = "OutputName";
	protected static final String enableDefaultKey = "enableDefault";
	protected static final String filterIdxKey = "filterIdx";

	protected static SharedPreferences settings = null;

	private static int RESULT_LOAD_IMAGE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// List available resources in raw and set mosaic filters
		java.lang.reflect.Field[] fields=R.raw.class.getFields();
		mFilters = new MosaicFilter[fields.length];
		for(int count=0; count < fields.length; count++){
			try {
				// Get index from field
				int id = fields[count].getInt(fields[count]);
				//System.out.println("[LOG] id is: " + id);
				// Read resource
				mFilters[count] = readPGMFile(id);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// Get configuration parameters
		settings = getSharedPreferences(settingsFile, Context.MODE_PRIVATE);

		// Set "Load Image" button
		Button buttonLoadImage = (Button) findViewById(R.id.b_select_img);
		buttonLoadImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// Load image from gallery
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
	}
	
	// Read PGM file and store information
	public MosaicFilter readPGMFile(int resId) {
		// Format of the PGM file name is "token1_token2_token3"
		// token1 corresponds to the shape
		// token2 to width x height
		// token3 to the number of filter available
		MosaicFilter mos = new MosaicFilter();
		// Get file name
		String pgmFilename = getApplicationContext().getResources().getResourceEntryName(resId);
		//System.out.println("[LOG] pgmFilename is: " + pgmFilename);
		// Split filename to retrieve info
		String tokens[] = pgmFilename.split("_");
		//System.out.println("[LOG] Tokens is: " + tokens);
		String name = tokens[0] + "_" + tokens[1];
		//System.out.println("[LOG] Name is: " + name);
		String token2[] = tokens[1].split("x");
		//System.out.println("[LOG] Token2[0] is: " + token2[0] + " and Token2[1] is: " + token2[1]);
		int width = Integer.parseInt( token2[0] );
		//System.out.println("[LOG] width is: " + width);
		int height = Integer.parseInt( token2[1] );
		//System.out.println("[LOG] height is: " + height);
		int nbFilters = Integer.parseInt( tokens[2] );
		//System.out.println("[LOG] nbFilters is: " + nbFilters);
		
		Resources res = getResources();
		InputStream in_s = res.openRawResource(resId);
		int[][] filters = new int[nbFilters][height * width];

		try {
		    BufferedReader br = new BufferedReader(new InputStreamReader(in_s, "UTF_8" ));
		    String line;
		    int i = 0; // filter
		    int j = 0; // width * height
		    
		    // Jump to 6th line
		    /*for(int k=0; k < 5; k++) {
		    	br.readLine();
			}*/
		    line = br.readLine(); // 1st line corresponds to PGM format P2(ASCII) expected
		    
		    if( ! line.equals("P2"))
		    	throw new IOException("ERROR: PGM file type is not P2.");
		    line = br.readLine(); // 2nd line corresponds to a comment we don't care about
		    line = br.readLine(); // 3rd line corresponds to "width nbFilters*height"
		    if( ! line.equals( width + " " + nbFilters * height ) )
		    	throw new IOException("ERROR: PGM file dimensions are not " + width + "x" + nbFilters * height + "." );
		    line = br.readLine(); // 4th line corresponds to maximum grey value
		    if(Integer.parseInt(line) > 255)
		    	throw new IOException("ERROR: PGM file maximum grey value is more than 255.");
		    line = br.readLine(); // 5th GARBAGE (?) Just skip it
		    
		    while ((line = br.readLine()) != null) {
		    	// Retrieve value of alpha canal
		    	filters[i][j] = ( Integer.parseInt( line ) << 24 ) | 0x00ffffff;
		    	//System.out.println("[LOG] filters[" + i + "][" + j + "] = " + Integer.toHexString(filters[i][j]) );
		    	
		    	if( j < width*height - 1 )
		    		j++;
		    	else {
		    		j = 0;
		    		i++;
		    		//System.out.println("[LOG] increment i");
		    	}
		    }
		    
		    br.close();
		}
		catch (IOException e) {
		    //You'll need to add proper error handling here
			System.out.println("[readPGMfile(" + pgmFilename + ")] " + e.getMessage());
		}
		
		mos.setFilter(name, height, width, nbFilters, filters);
		
		return mos;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// If an image is loaded from the gallery then display
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			// Launch DisplayActivity
			Intent i = new Intent(MainActivity.this, DisplayActivity.class);
			i.putExtra("picturePath", picturePath); // Send path to
													// DisplayActivity
			startActivity(i);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Manages user selection in the menu
		super.onOptionsItemSelected(item);

		int menuId = item.getItemId();
		if (menuId == R.id.menu_settings) {
			// Launch SettingsActivity
			Intent i = new Intent(MainActivity.this, SettingsActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
		// else if(menuId = ...) {....}

		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// When the user center presses back
			finish();
			return true;
		}
		return false;
	}
}
